package com.itttq.gshop.admin.controller;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.itttq.gshop.domain.to.ResultTo;
import com.itttq.gshop.generic.util.Constants;

@RestController
public class CommonController extends GenericController {
	private static final long serialVersionUID = 2574898959274772468L;
	// 图片上传目录，
	@Value("${gshop.file.img.upload}")
	public String imgUploadPath;
	// 图片URL地址，http://img.xx.com
	@Value("${gshop.file.img.url}")
	public String imgUrlPath;

	/**
	 * 上传单个图片文件<br>
	 * 这里这里用的是MultipartFile file参数,所以前台就要用< input type="file" name="file"/ >,参数名称file与input的name属性名对应
	 * @param dir	上传目录
	 * @param file	文件内容
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public ResultTo uploadImage(Integer dirType, MultipartFile file) throws IOException {
		ResultTo rt = new ResultTo(ResultTo.FAIL);
		if (null == file || file.isEmpty() || null == dirType || dirType < 1 || null == Constants.UPLOAD_DIR.get(dirType)) {
			rt.setCode(ResultTo.PARAM_INCORRECT);
			rt.setMsg("传入参数不正确！");
			return rt;
		}
		String fileType = !file.getOriginalFilename().contains(Constants.SEPARATOR_SPOT) ? "" 
				: file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(Constants.SEPARATOR_SPOT));
		if(!Constants.IMG_TYPES.contains(fileType)) {
			// 判断类型
			rt.setCode(ResultTo.FILE_TYPE);
			rt.setMsg("文件类型错误，只支持：png、gif、jpg、jpeg");
		} else {
			try {
				String filePath = Constants.SEPARATOR_BACKSLASH + Constants.UPLOAD_DIR.get(dirType)
						 + Constants.SEPARATOR_BACKSLASH + Constants.getFilenameByTime(null) +fileType;
				// 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
				// 此处也可以使用Spring提供的MultipartFile.transferTo(File
				// dest)方法实现文件的上传
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(imgUploadPath + filePath));
				rt.setCode(ResultTo.SUCCESS);
				rt.setMsg(imgUrlPath + filePath);
			} catch (IOException e) {
				e.printStackTrace();
				rt.setCode(ResultTo.PARAM_INCORRECT);
				rt.setMsg("文件上传失败，请重试");
			}
		}
		return rt;
	}
}
